#include <Bonezegei_DHT11.h>
#include <WiFi.h>


#define LED_BLUE 2 // 定义LED管脚

const char* ssid = "xiaomate.cn_5G";
const char* password = "31637200";
WiFiServer server(80); // 设置服务器端口为80

Bonezegei_DHT11 dht(14);   //设置dht io为14引脚

void setup() {
  Serial.begin(115200);
  dht.begin();

    // 连接WiFi网络
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // 打印ESP32的IP地址
  Serial.print("ESP32 IP Address: ");
  Serial.println(WiFi.localIP());

  // 启动服务器
  server.begin();
  Serial.println("Server started");
  //设置LED管脚为输出模式
  pinMode(LED_BLUE,OUTPUT);


}
 
void loop() {
 
  digitalWrite(LED_BLUE,HIGH);
 
    // 等待客户端连接
  WiFiClient client = server.available();
  if (client) {
    
    // 读取客户端请求
    String request = client.readStringUntil('\r');
    Serial.println("Request: " + request);
    //在处理完请求后通常会调用client.flush()方法来清空输入缓冲区 以确保下一个请求能够被正确处理。
    client.flush();

    // 检查请求路径中是否包含"/on"的子字符串 没有则返回-1
    if (request.indexOf("/on") != -1) {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.println("LED ON");
    } else if (request.indexOf("/off") != -1) {
      digitalWrite(LED_BUILTIN, LOW);
      Serial.println("LED OFF");
    }

    // 返回响应
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println();
    client.println("<!DOCTYPE HTML>");
    client.println("<html>");
    client.println("<head><title>ESP32 Panel</title><meta charset='UTF-8'></head>");
    client.println("<body>");
    client.println("<h1>ESP32 Panel</h1>");
  if (dht.getData()) {                         
    float tempDeg = dht.getTemperature();      
    float tempFar = dht.getTemperature(true);  
    char res[100];
    int hum = dht.getHumidity();               
    //Serial.printf("Temperature: %0.1lf°C  %0.1lf°F Humidity:%d \n", tempDeg, tempFar, hum);
    //delay(20000); 
    sprintf(res, "<h2>Temperature: %0.1f°C  <br>  Humidity:%d \n </h2>", tempDeg, hum); 
    client.println(res);

  }



    // client.println("<p>Click <a href=\"/on\">here</a> to turn the LED on</p>");
    // client.println("<p>Click <a href=\"/off\">here</a> to turn the LED off</p>");
    client.println("</body>");
    client.println("</html>");

    // 断开客户端连接
    client.stop();
  }
}